package controllers

import (
	"beego_background_framework/models"
	"beego_background_framework/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"strconv"
)

//系统管理员管理
type AdminSysController struct {
	BaseController
}

//会员列表
func (c *AdminSysController) Index(){
	pageNo, _ := c.GetInt("page",1)
	pageSize := c.GetDefaultPageSize()
	userName := c.GetString("username","")
	startDate := c.GetString("start","")
	endDate := c.GetString("end","")

	o := orm.NewOrm()

	//查询所有管理员列表
	var list[]*models.AdminUser
	//设置排序
	qs := o.QueryTable(new(models.AdminUser)).
		OrderBy("-id").
		Offset(c.GetPageOffset(pageNo,pageSize)).
		Limit(pageSize).
		Filter("username__contains",userName)
	//筛选时间
	if startDate != "" && endDate != ""{
		qs = qs.Filter("created_at__gte",startDate).Filter("created_at__lte",endDate)
	}else if startDate != ""{
		qs = qs.Filter("created_at__gte",startDate)
	}else if endDate != ""{
		qs = qs.Filter("created_at__lte",endDate)
	}
	//管理员总数
	cnt,_ := qs.Count()
	//数据列表
	_, _ = qs.All(&list)
	//处理分页
	paginator := utils.PageUtil(int(cnt),pageSize,c.Ctx.Request.RequestURI,list)
	c.Data["list"] = list
	c.Data["paginator"] = paginator.ToString()
	c.Data["username"] = userName
	c.Data["start_date"] = startDate
	c.Data["end_date"] = endDate

	c.SetTpl("admin_sys/index.html")
}

func (c *AdminSysController) Create()  {
	//查询所有角色
	o := orm.NewOrm()
	var adminGroups []*models.AdminGroup
	_, _ = o.QueryTable(new(models.AdminGroup)).Filter("status", 1).All(&adminGroups,"Id","Name")

	c.Data["groups"] = adminGroups
	c.SetTpl("admin_sys/create.html")
}

func (c *AdminSysController) Add()  {
	var adminUser models.AdminUser
	_ = c.Ctx.Input.Bind(&adminUser.Username, "username")
	_ = c.Ctx.Input.Bind(&adminUser.Sex, "sex")
	_ = c.Ctx.Input.Bind(&adminUser.Phone, "phone")
	_ = c.Ctx.Input.Bind(&adminUser.Email, "email")
	_ = c.Ctx.Input.Bind(&adminUser.Password, "pass")
	var groups []string
	_ = c.Ctx.Input.Bind(&groups, "group")
	//清除空值
	groups = utils.TrimSlice(groups)
	if len(groups) == 0{
		c.ApiError("至少要选择绑定一个角色",nil)
	}
	repass := c.GetString("repass")
	// 验证字段
	valid := validation.Validation{}
	valid.Required(adminUser.Username,"username").Message("用户名不允许为空")
	valid.MinSize(adminUser.Username,2,"username").Message("用户名长度不能小于2位")
	valid.MaxSize(adminUser.Username,12,"username").Message("用户名长度不能大于12位")
	valid.Email(adminUser.Email,"email").Message("邮箱格式不正确")
	valid.Mobile(adminUser.Phone,"phone").Message("手机号码格式不正确")
	valid.MinSize(adminUser.Password,6,"pass").Message("密码长度不能小于6位")
	valid.MaxSize(adminUser.Password,20,"pass").Message("密码长度不能大于20位")
	if repass != adminUser.Password{
		c.ApiError("两次密码不一致",nil)
	}
	if valid.HasErrors(){
		for _,err := range valid.Errors{
			c.ApiError(err.Message,nil)
		}
	}
	o := orm.NewOrm()
	//检查用户名是否已使用
	num, err := o.QueryTable(new(models.AdminUser)).Filter("username", adminUser.Username).Count()
	if err != nil{
		c.ApiError("出错了："+err.Error(),nil)
	}
	if num >=1{
		c.ApiError("当前用户名已存在",nil)
	}
	adminUser.Status = 1 //设置为可用
	adminUser.Password = utils.Md5Encode(adminUser.Password + beego.AppConfig.String("pwd_salt")) //加密密码
	//开始事务
	err = o.Begin()
	if err != nil{
		_ = o.Rollback()
		c.ApiError(err.Error(),nil)
	}
	_, err = o.Insert(&adminUser)
	if err != nil{
		_ = o.Rollback()
		c.ApiError(err.Error(),nil)
	}
	m2m := o.QueryM2M(&adminUser,"AdminGroup")
	var adminGroupList []models.AdminGroup
	for _,v := range groups{
		u, _ := strconv.Atoi(v)
		adminGroupList = append(adminGroupList,models.AdminGroup{Id:uint(u)})
	}
	_, err = m2m.Add(adminGroupList)
	if err != nil{
		_ = o.Rollback()
		c.ApiError(err.Error(),nil)
	}

	//提交事务
	_ = o.Commit()

	c.ApiSuccess("操作成功","")
}

func (c *AdminSysController) Edit(){
	id, err := c.GetUint64(":id")
	if err != nil{
		c.ApiError("数据类型有误",nil)
	}
	//查询用户数据
	o := orm.NewOrm()
	adminUser := models.AdminUser{Id: uint(id)}
	err = o.Read(&adminUser)
	if err == orm.ErrNoRows{
		c.ApiError("未找到信息",nil)
	}
	//加载管理组
	_, _ = o.LoadRelated(&adminUser, "AdminGroup")

	//查询所有角色
	var adminGroups []*models.AdminGroup
	_, _ = o.QueryTable(new(models.AdminGroup)).Filter("status", 1).All(&adminGroups,"Id","Name")
	c.Data["groups"] = adminGroups
	c.Data["adminUser"] = adminUser
	c.SetTpl("admin_sys/edit.html")
}

func (c *AdminSysController) Update(){
	var adminUser models.AdminUser
	o := orm.NewOrm()
	_ = c.Ctx.Input.Bind(&adminUser.Id, ":id")
	err := o.Read(&adminUser)
	if err != nil{
		c.ApiError("查询失败",nil)
	}
	_ = c.Ctx.Input.Bind(&adminUser.Username, "username")
	_ = c.Ctx.Input.Bind(&adminUser.Sex, "sex")
	_ = c.Ctx.Input.Bind(&adminUser.Phone, "phone")
	_ = c.Ctx.Input.Bind(&adminUser.Email, "email")
	pass := c.GetString("pass")
	if pass != "" {
		adminUser.Password = utils.Md5Encode(pass + beego.AppConfig.String("pwd_salt"))
	}
	var groups []string
	_ = c.Ctx.Input.Bind(&groups, "group")
	//清除空值
	groups = utils.TrimSlice(groups)
	if len(groups) == 0{
		c.ApiError("至少要选择绑定一个角色",nil)
	}
	// 验证字段
	valid := validation.Validation{}
	valid.Required(adminUser.Username,"username").Message("用户名不允许为空")
	valid.MinSize(adminUser.Username,2,"username").Message("用户名长度不能小于2位")
	valid.MaxSize(adminUser.Username,12,"username").Message("用户名长度不能大于12位")
	valid.Email(adminUser.Email,"email").Message("邮箱格式不正确")
	valid.Mobile(adminUser.Phone,"phone").Message("手机号码格式不正确")
	if valid.HasErrors(){
		for _,err := range valid.Errors{
			c.ApiError(err.Message,nil)
		}
	}
	if adminUser.Username != c.GetString("username"){
		//检查用户名是否已使用
		num, err := o.QueryTable(new(models.AdminUser)).Filter("username", adminUser.Username).Count()
		if err != nil{
			c.ApiError("出错了："+err.Error(),nil)
		}
		if num >=1{
			c.ApiError("当前用户名已存在",nil)
		}
	}
	//开始事务
	err = o.Begin()
	if err != nil{
		_ = o.Rollback()
		c.ApiError(err.Error(),nil)
	}
	_, err = o.Update(&adminUser)
	if err != nil{
		_ = o.Rollback()
		c.ApiError(err.Error(),nil)
	}
	m2m := o.QueryM2M(&adminUser,"AdminGroup")
	//清除之前的关系
	_, err = m2m.Clear()
	if err != nil{
		_ = o.Rollback()
		c.ApiError(err.Error(),nil)
	}

	var adminGroupList []models.AdminGroup
	for _,v := range groups{
		u, _ := strconv.Atoi(v)
		adminGroupList = append(adminGroupList,models.AdminGroup{Id:uint(u)})
	}
	_, err = m2m.Add(adminGroupList)
	if err != nil{
		_ = o.Rollback()
		c.ApiError(err.Error(),nil)
	}

	//提交事务
	_ = o.Commit()

	c.ApiSuccess("操作成功",nil)
}

func (c *AdminSysController) Destroy(){
	id, _ := c.GetUint64(":id")
	o := orm.NewOrm()
	if num,err :=o.Delete(&models.AdminUser{Id: uint(id)});err == nil{
		if num > 0{
			c.ApiSuccess("操作成功",nil)
		}
	}
	c.ApiError("操作失败",nil)
}

// 设置会员的状态
func (c *AdminSysController) UpdateStatus(){
	id, _ := c.GetUint64("id")
	if id == 1{
		c.ApiError("不允许禁用超级管理员",nil)
	}
	adminUser := models.AdminUser{Id:uint(id)}
	o := orm.NewOrm()
	if o.Read(&adminUser) == nil{
		//_, _ = o.LoadRelated(&adminUser, "AdminGroup")
		//设置会员状态
		if adminUser.Status == 2{
			adminUser.Status = 1
		}else if adminUser.Status == 1 {
			adminUser.Status = 2
		}
		if num, err := o.Update(&adminUser); err == nil{
			c.ApiSuccess("操作成功", map[string]interface{}{"status":adminUser.Status,"num":num})
		}
	}
	c.ApiError("操作失败",nil)
}
